import core.auto_test
import core.data_read
from core import serial_port
import os
from logger.logger import Log

#    配置文件读取模块

class Config:
    arg = None

    def read_excel(self) -> core.auto_test.AutoTest:
        if os.path.exists(self.xlsx_path):
            # 从config.toml文件中读取excel和case的值，进入excel，找到命名为[case]的sheet，并赋值给gateway, node, test_case
            gateway, node, test_case = core.data_read.read_excel_data(self.xlsx_path, self.case)
            # 创建一个AutoTest对象
            if self.at is None:
                self.at = core.auto_test.AutoTest()
            self.at.set_case_sample(gateway, node, test_case)
        # 返回一个AutoTest对象
        return self.at

    def start(self):
        try:
            # 获取可用串口列表
            port_list = serial_port.load_port_list()
            if Config.arg['Gateway']['Connect'] == 'SSH':
                self.port = port_list[0].device
            else:
                if len(port_list) < 2:
                    Log.logger.error('串口直接网关测试模式，检测到串口数量少于2！')
                    return
                elif Config.arg['TestCase']['serialPort'] == Config.arg['Gateway']['SerialPort']:
                    Log.logger.error('检测到网关串口号与模组串口号相同！！！')
                    return
                else:
                    self.port = Config.arg['TestCase']['serialPort']
        except Exception as e:
            Log.logger.error("[Get Serial Port Error] {}".format(e))

        try:
            if self.at is None:
                self.at = core.auto_test.AutoTest()
            # 从config.toml文件中读取excel和case的值，进入excel，找到命名为case的sheet，并赋值给gateway, node, test_case
            gateway, node, test_case = core.data_read.read_excel_data(self.xlsx_path, self.case)
            self.at.set_case_sample(gateway, node, test_case)
        except Exception as e:
            Log.logger.error("[Read Excel Error] {}".format(e))
            return
        # port:28行获取，bitrate:['TestCase']['bitrate']，server:server
        self.at.start(self.port, self.bitrate, self.server)
        self.test_result = self.at.test_result

    def __init__(self, server):
        self.at = None
        self.port = None
        self.bitrate = int(Config.arg['TestCase']['bitrate'])
        core.auto_test.AutoTest.output = None
        self.server = server
        self.xlsx_path = Config.arg['TestCase']['excel']
        self.case = Config.arg['TestCase']['case']
        self.read_excel()
